package Producer

import (
	"bufio"
	"fmt"
	"github.com/nsqio/go-nsq"
	"os"
	"strings"
)

var producer *nsq.Producer

// 初始化生产者
func initProducer(str string) (err error) {
	config := nsq.NewConfig()
	producer, err = nsq.NewProducer(str, config)
	if err != nil {
		fmt.Printf("create producer failed, err:%v\n", err)
		return err
	}
	return nil
}
func MakeNewProducer(nsqlAddress string)(  producer *nsq.Producer,err error){
	config:=nsq.NewConfig()
	newProducer,err:=nsq.NewProducer(nsqlAddress,config)
	if err!=nil{
		fmt.Println("生成producer的时候出现了问题")
		return nil,err
	}
	return newProducer,err
}
func send_Message(MessageProducer *nsq.Producer,topic_name string){
	reader := bufio.NewReader(os.Stdin)
	for {
		data, err := reader.ReadString('\n')
		if err != nil {
			fmt.Printf("read string from stdin failed, err:%v\n", err)
			continue
		}
		data = strings.TrimSpace(data)
		if strings.ToUpper(data) == "Q" { // 输入Q退出
			break
		}
		// 向 'topic_demo' publish 数据
		err = MessageProducer.Publish(topic_name, []byte(data))
		if err != nil {
			fmt.Printf("publish msg to nsq failed, err:%v\n", err)
			continue
		}
	}
}
func MakeProducer(){
	MessageProducer,_:=MakeNewProducer("101.91.158.87:4150")
	send_Message(MessageProducer,"topic_demo")
}
